package cn.sc.summer.sentinel.exception;

import cn.sc.summer.constant.model.Result;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author a-xin
 * @description 自定义sentinel异常返回信息
 * @belongsProject SummerCloud
 * @belongsPackage cn.sc.summer.sentinel.exception
 * @date 2025-02-14  15:49
 */
@Component("SentinelExceptionHandler")
public class SentinelExceptionHandler implements BlockExceptionHandler {

    /**
     * Handle the request when blocked.
     *
     * @param request   Servlet request
     * @param response  Servlet response
     * @param exception the block exception
     * @throws Exception users may throw out the BlockException or other error occurs
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException exception) throws Exception {
        exception.printStackTrace();
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.getWriter().write(JSONObject.toJSONString(Result.fail(exception.getMessage())));
    }

}
